package com.zhouyu.gamecommunity.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.zhouyu.gamecommunity.entity.Result;
import com.zhouyu.gamecommunity.utils.HttpRequestUtil;
import com.zhouyu.gamecommunity.utils.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class WorkController {

    @PostMapping("/word")
    public void createWord(MultipartFile file, String id, HttpServletResponse response) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> maps = reader.readAll();
            List<Map<String, Object>> collect = maps.stream().filter(map -> map.get("问题单号").equals(id)).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                Map<String, Object> map = collect.get(0);
                String no = map.get("问题单号").toString();
                String description = map.get("简要描述").toString();
                // 找到第二个"【"的位置
                int start = description.indexOf("【", description.indexOf("【") + 1);
                // 找到对应的"】"的位置
                int end = description.indexOf("】", start);
                // 截取内容（注意加1是为了跳过"【"）
                String name = description.substring(start + 1, end);
                Map<String, Object> param = new HashMap<>();
                param.put("id", no);
                param.put("name", name);
                param.put("description", description);
                File word = WordUtil.createWordByTemplate("template.docx", param);

                // 设置响应内容类型（根据文件格式选择）
                // .doc格式: application/msword
                // .docx格式: application/vnd.openxmlformats-officedocument.wordprocessingml.document
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

                // 设置响应头，指定文件名（解决中文乱码问题）
                String fileName = id + "_" + name + "_周余.docx";
                fileName = URLEncoder.encode(fileName, "UTF-8");

                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setCharacterEncoding("UTF-8");
                response.setContentLength((int) word.length());

                // 读取文件并写入响应流
                try (FileInputStream fis = new FileInputStream(word);
                     BufferedInputStream bis = new BufferedInputStream(fis);
                     OutputStream os = response.getOutputStream()) {

                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                    os.flush();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/api/txt")
    public Result<String> createApiTxt(@RequestBody JSONObject param, HttpServletRequest request){
        String ipAddr = HttpRequestUtil.getIpAddr(request);
        log.info("请求IP地址: " + ipAddr);
        String name = param.getString("name");
        String result = param.getString("result");
        String fileName = name + ".txt";
        //文件位置
        File dir = new File("F:\\workSpace\\小程序\\api");
        //保存的文件
        File file = new File(dir, fileName);
        // 写入文件内容
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(result);
            writer.flush();
            return Result.success("文件已成功生成: " + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("生成文件异常: " + e.getMessage());
        }
    }

    @PostMapping("/upload")
    public Result<JSONObject> uploadFile(MultipartFile file) {
        JSONObject result = new JSONObject();
        try {
            file.transferTo(new File("F:\\workSpace\\小程序\\upload\\" + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(500,"上传文件失败");
        }
        result.put("fileName", file.getOriginalFilename());
        result.put("contentType", file.getContentType());
        result.put("size", file.getSize());
        return Result.success(result);
    }

    @GetMapping("/test")
    public Result<String> test(){
        return Result.success();
    }
}
